package com.own.business.system.user.business.core;

import com.own.business.system.user.business.hook.GetSystemUserHook;
import com.own.business.system.user.entity.vo.SystemUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * GetSystemUserSpringHook
 *
 * @author chenxueli
 * @date 2023-06-18 11:24:00
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class GetSystemUserSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final List<GetSystemUserHook> HOOK_LIST = new ArrayList<>();
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 同步执行
     *
     * @param userId 用户id
     * @param vo     用户信息
     */
    public void use(Long userId, SystemUserVo vo) {
        HOOK_LIST.forEach(hook -> hook.getSystemUserHook(userId, vo));
    }

    /**
     * 异步执行
     *
     * @param userId 用户id
     * @param vo     用户信息
     */
    public void useParallel(Long userId, SystemUserVo vo) {
        HOOK_LIST.parallelStream().forEach(hook -> hook.getSystemUserHook(userId, vo));
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(GetSystemUserHook.class).forEach((key, hook) -> {
                HOOK_LIST.add(hook);
                log.debug("登录动作钩子方法===>【{}】完成注册", key);
            });
        }
    }

}
